const express = require('express')

const app = express()

app.listen(3000,function(){
console.log('3000端口开启了，可以访问: http://localhost:3000')
})
const path = require('path')
const fs = require('fs')
const mysql = require('mysql')
app.set('view engine','ejs')
const timeStamp = require('time-stamp')
const serveFavicon = require('serve-favicon')
const { render } = require('ejs')
app.use(serveFavicon('favicon.ico'))
app.use( express.urlencoded( {extended:false} ) )
app.use( '/static',express.static('static') )
const connObj = mysql.createConnection({
    host:'localhost',
    user:'root',
    password:'root',
    port:3306,
    database:'0803web'
})

app.get('/',(req,res)=>{
    res.send('我是网站的首页')
})

app.get('/login',(req,res) =>{
    res.render('login')
})

app.get('/register',(req,res) =>{
    res.render('register')
})
app.post('/login',function(req,res,next) {
    let { username,password } = req.body
    // 去除左右空格
    let reg = /^\s+|\s+$/g
    username = username.replace(reg,'')
    if (username == '' || password == '') {
        res.send('请传递必要参数')
        return
    }
    
    let sql = `SELECT * FROM users WHERE username = '${username}' AND password ='${password}'`
    connObj.query( sql,(err,result)=>{
        if (result.length >0) {
            res.send('登陆成功')
        } else {
            res.send('用户名或密码错误')
        }
    })
    
    

})

app.post('/register',function(req,res,next) {
    let { username,password,repwd } = req.body
    // 去除左右空格
    let reg = /^\s+|\s+$/g
    username = username.replace(reg,'')
    if (username == '' || password == '' || repwd=='') {
        res.send('请传递必要参数')
        return
    }
    if( password != repwd ){
        res.send('两次密码不一致')
        return
    }
    let time = timeStamp()
    let sql0 = `SELECT * FROM users WHERE username = '${username}' `
    connObj.query( sql0,(err,result)=>{
        if (result.length > 0) {
            res.send('用户名已被占用')
            return
        } 
        let sql1 = `INSERT INTO users ( username,password,regtime ) VALUES ( '${username}','${password}', ${time})`
        connObj.query( sql1,(err,result)=>{
            res.send('注册成功')
        })
        
    })
    
})
